<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="5" :xs="24">
        <my-dept-tree v-model="queryParams.deptId" @change="handleDeptChange" ref="deptTree"></my-dept-tree>
      </el-col>
      <el-col :span="19" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
          <el-form-item label="作业项目" prop="beyondQuota">
            <el-input v-model="queryParams.beyondQuota" placeholder="作业项目"/>
          </el-form-item>
          <el-form-item label="日期" prop="date">
            <date-range-picker startPlaceholder="开始日期" endPlaceholder="结束日期" v-model="dateRange"></date-range-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['cases:statisticsMouth:export']" type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
          </el-col>
        </el-row>
        <el-table v-loading="loading" :row-style="rowStyle" :highlight-current-row="true" :data="tableData" :span-method="spanMethod" max-height="700">
          <el-table-column type="index" :index="(index)=>tableIndex(queryParams.pageSize,queryParams.pageNum,index)" label="序号" align="center" fixed="left" />
          <el-table-column label="日期" align="center" prop="dealDate" width="150" fixed="left"/>
          <el-table-column label="工作内容（严格按照定额标准项目名称）" align="center" prop="quantitativeTypeName" width="150" fixed="left"/>
          <el-table-column label="劳务形式" align="center" prop="type" width="150">
            <el-table-column label="外包" align="center" prop="outsourcedNum" width="100">
              <template slot-scope="scope">
                <i class="el-icon-check" v-if="scope.row.type == 3"/>
              </template>
            </el-table-column>
            <el-table-column label="自主" align="center" prop="insourcedNum" width="100"> 
              <template slot-scope="scope">
                <i class="el-icon-check" v-if="scope.row.type == 2" />
              </template>
            </el-table-column>
            <el-table-column label="自主+外包" align="center" prop="username" width="100">
              <template slot-scope="scope">
                <i class="el-icon-check" v-if="scope.row.type == 1" />
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="施工位置" align="center" prop="locationNum" width="150" />
          <el-table-column label="人数" align="center" width="150">
            <el-table-column label="外雇" align="center" prop="outSourceNum" width="150" >
                 <template slot-scope="scope">
                  <span>{{scope.row.outSourceNum || "0"}}</span>
                </template>
            </el-table-column>
            <el-table-column label="自有" align="center" prop="insourcedNum" width="150" >
                <template slot-scope="scope">
                  <span>{{scope.row.insourcedNum || "0"}}</span>
                </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="小计" align="center" prop="insourcedName" width="150">
            <template slot-scope="scope">
              <span>{{Number(scope.row.outSourceNum) + Number(scope.row.insourcedNum)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="自有人员姓名" align="center" prop="insourcedName" width="150" />
          <el-table-column label="完成工程总量" align="center" prop="qualifiedNum" width="150" />
          <el-table-column label="工程量单位" align="center" prop="quantitativeRatedUnitValue" width="150" />
          <el-table-column label="平均每人工程量" align="center" prop="perDay" width="150" />
          <el-table-column label="定额标准" align="center" prop="quantitativeTypeValue" width="150" />
          <el-table-column label="完成系数" align="center" prop="completionCoefficient" width="150" />
          <el-table-column label="日均系数" align="center" prop="averageDailyCoefficient" width="150" />

          <el-table-column label="考核结果" align="center" prop="auditResult" width="150">
            <el-table-column label="达标" align="center" width="150">
              <template slot-scope="scope">
                <i class="el-icon-check" v-if="scope.row.auditResult == '达标'" />
              </template>
            </el-table-column>
            <el-table-column label="未达标" align="center" width="150">
              <template slot-scope="scope">
                <i class="el-icon-check" v-if="scope.row.auditResult == '未达标'" />
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="考核人" align="center" prop="assessorName" width="150" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">查看明细</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="1000px" append-to-body :before-close="handleClose">
      <el-table v-loading="detailLoading" :data="detailTableData">
        <el-table-column type="index" :index="(index)=>tableIndex(queryParams.pageSize,queryParams.pageNum,index)" label="序号" align="center" />
        <el-table-column label="路线名称" align="center" prop="roadName" />
        <el-table-column label="位置桩号" align="center" prop="locationNum"></el-table-column>
        <el-table-column label="上报人" align="center" prop="createUserName" width="180" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
        <el-table-column label="类型" align="center" prop="iTroubleshooting" width="100">
          <template slot-scope="scope">
            {{getCheckTypeName(scope.row.iTroubleshooting)}}
          </template>
        </el-table-column>
        <el-table-column label="作业项目" align="center" prop="iPart" width="150">
          <template slot-scope="scope">
            {{ scope.row.taskType == '1'? scope.row.quantitativeTypeName : scope.row.beyondQuota }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="dataStatus" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.jl_data_status" :value="scope.row.dataStatus"></dict-tag>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="detailTotal > 0" :total="detailTotal" :page.sync="detailQueryParams.pageNum" :limit.sync="detailQueryParams.pageSize" @pagination="getDetailList" />

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="updateDialogTitle" :close-on-click-modal="false" :visible.sync="updateDialogOpen" width="400px" append-to-body :before-close="handleCloseUpdateDialog">
      <el-form :model="form" ref="form" size="small" :rules="rules">
        <el-form-item label="审核结果" prop="auditResult">
          <el-radio-group v-model="form.auditResult">
            <el-radio label="达标"></el-radio>
            <el-radio label="未达标"></el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancelUpdate">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listStatisticsMouth,
  getStatisticsMouthDetail,
  checkStatisticsMouth,
} from "@/api/cases/statisticsMouth";
import { listTroubleShooting } from "@/api/cases/troubleShooting";
import { listCommonCheckType } from '@/api/cases/commonCheckType'
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import CommonCheckTypeSelect from '../../../components/Select/CommonCheckTypeSelect.vue';
import DictSelect from '../../../components/Select/DictSelect.vue';
import DeptUserSelect from '../../../components/Select/DeptUserSelect.vue';
import DeptTree from '../../../components/Tree/DeptTree.vue';
import DateRangePicker from '../../../components/DatePicker/DateRangePicker.vue';
import { defaultDateDangeInMonth,toFixed } from "@/utils/index.js"
import { mapGetters } from 'vuex';
import { groupBy } from 'lodash';
import MyDeptTree from '../../../components/Tree/MyDeptTree.vue';
export default {
  name: "statisticsMouth",
  dicts: ["jl_cases_damage_level", "jl_cases_repair_method", "jl_data_status"],
  components: { DictSelect, CommonCheckTypeSelect, DictSelect, DeptUserSelect, DeptTree, DateRangePicker, MyDeptTree },
  data() {
    return {
      // 禁用表单
      isDisabled: false,
      // 遮罩层
      loading: true,
      //明细遮罩层
      detailLoading: true,
      // 选中数组
      ids: [],
      //选中行
      selection: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      tableData: [],
      // 明细总条数
      detailTotal: 0,
      // 明细表格数据
      detailTableData: [],
      // 弹出层标题
      title: "",
      // 更新弹出层标题
      updateDialogTitle: "",
      // 是否显示弹出层
      open: false,
      // 是否显示更新弹出层
      updateDialogOpen: false,
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100000,
        startDate: void 0,
        endDate: void 0,
        deptId: void 0,
        beyondQuota: void 0
      },
      //明细列表查询参数
      detailQueryParams: {
        assignDate: void 0,
        deptId: void 0,
        quantitativeTypeId: void 0,
        dataStatus: 3,
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      rowspan: {},//行的合并
      averageDailyCoefficient:{},//日均系数
    };
  },
  async created() {
    this.dateRange = defaultDateDangeInMonth()
    await this.getCheckTypes();
  },
  computed: {
    ...mapGetters(["userId"]),
    // 表单校验
    rules() {
      return {
        auditResult: [
          { required: true, message: "审核结果不能为空", trigger: "blur" },
        ],
      }
    },
  },
  watch: {
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.queryParams.startDate = this.dateRange[0];
      this.queryParams.endDate = this.dateRange[1];
      this.loading = true;
      this.rowspan = {};
      this.averageDailyCoefficient = {};
      listStatisticsMouth(this.queryParams).then((response) => {
        let tableData = response.rows;
        tableData = tableData.sort((a,b)=>{
          return a.dealDate - b.dealDate
        })
        let groupByResult = groupBy(tableData, "dealDate");
        let rowIndex = 0;
        Object.keys(groupByResult).forEach((dealDate) => {
          let rows = groupByResult[dealDate];
          let rowspan = rows.length;
          let completionCoefficient = 0;
          rows.forEach(row=>{
            completionCoefficient += Number(row.completionCoefficient);
          })
          let averageDailyCoefficient = toFixed((completionCoefficient / rowspan),2);
          this.rowspan[rowIndex] = rowspan;
          this.averageDailyCoefficient[rowIndex] = averageDailyCoefficient;
          rowIndex += rowspan;
        })
        tableData.forEach((row,index)=>{
          if(this.averageDailyCoefficient[index]){
            row.averageDailyCoefficient = this.averageDailyCoefficient[index]
          }
        })
        this.tableData = tableData;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: void 0,
        quotaStandard: void 0,
      };
      this.resetForm("form");
    },
    /**
     * 部门改变
     */
    handleDeptChange(){
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = defaultDateDangeInMonth();
      this.handleQuery();
    },
    /** 查看 */
    handleDetail(row) {
      const assignDate = row.dealDate;
      const deptId = this.queryParams.deptId;
      const quantitativeTypeId = row.quantitativeTypeId;
      const beyondQuota = row.quantitativeTypeName;
      this.detailLoading = true;
      this.open = true;
      this.title = "定额工作完成情况评价明细--" + row.deptName;
      this.detailQueryParams = {
        assignDate,
        deptId,
        quantitativeTypeId,
        beyondQuota,
        dataStatus: 3,
        pageNum: 1,
        pageSize: 10,
      };
      this.getDetailList();
    },
    /**
     * 获取明细列表
     */
    getDetailList() {
      listTroubleShooting(this.detailQueryParams).then((response) => {
        this.detailTableData = response.rows;
        this.detailTotal = response.total;
        this.detailLoading = false;
      });
    },
    /**
     * 审核
     */
    handleUpdateShyj(row) {
      this.updateDialogOpen = true;
      this.reset();
      this.form = Object.assign({ auditResult: '达标' }, row);
      this.updateDialogTitle = "审核"
    },
    /**
     * 提交表单
     */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let data = {
            deptId: this.queryParams.deptId,
            statisticsDate: this.form.dealDate,
            auditResult: this.form.auditResult,
            quantitativeTypeId: this.form.quantitativeTypeId
          }
          checkStatisticsMouth(data).then(({ code, data, msg }) => {
            if (code == 200) {
              this.$modal.msgSuccess("审核完成");
              this.handleCloseUpdateDialog();
              this.getList();
            } else {
              this.$modal.msgError(msg);
            }
          });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/cases/statisticsMouth/exportTest', {
        ...this.queryParams
      }, `工区评价_${new Date().getTime()}.xlsx`)
    },
    /**
     * 行样式
     */
    rowStyle() {
      return {
        "cursor": "pointer"
      }
    },
    /**
     * 根据日期的值合并行 
     */
    spanMethod({ row, column, rowIndex, columnIndex }) {
      if (column.property === "averageDailyCoefficient") {
        if (this.rowspan[rowIndex]) {
          return {
            rowspan: this.rowspan[rowIndex],
            colspan: 1,
          };
        }else{
          return {
            rowspan: 0,
            colspan: 1,
          };
        }
      }else{
          return {
            rowspan: 1,
            colspan: 1,
          };
      }
    },
    /**
     * 处理关闭
     */
    handleClose() {
      this.cancel();
    },
    /**
     * 隐藏
     */
    cancel() {
      this.open = false;
    },
    /**
     * 处理关闭
     */
    handleCloseUpdateDialog() {
      this.cancelUpdate();
    },
    /**
     * 取消更新
     */
    cancelUpdate() {
      this.updateDialogOpen = false;
    },
    /**
    * 获取类型
    */
    getCheckTypes() {
      let params = {
        status: 0,
        delFlag: 0
      }
      return new Promise((resolve, reject) => {
        listCommonCheckType(params).then(res => {
          this.checkTypes = res.data;
          resolve()
        }).catch(() => {
          this.checkTypes = [];
          reject()
        })
      })
    },
    /**
     * 获取检查的名称
     */
    getCheckTypeName(checkType) {
      let index = this.checkTypes.findIndex((item) => {
        return item.id == checkType;
      })
      if (index > -1) {
        return this.checkTypes[index].checkTypeName
      } else {
        return ""
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.form-title {
  padding: 2px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
}
.input-sperator {
  margin-right: 10px;
  margin-left: 10px;
  padding-bottom: 18px;
  line-height: 29px;
}
</style>
